import * as Blockly from 'blockly';
import { save } from '../core/serialization';
import { CodePanel } from './code-panel';

// 工作区管理类
export class WorkspaceManager {
  constructor(
    private workspace: Blockly.Workspace,
    private codePanel: CodePanel
  ) {
    this.workspace = workspace;
    this.codePanel = codePanel;
    this.setupChangeListener();
  }

  // 设置变化监听器
  setupChangeListener() {
    this.workspace.addChangeListener((e) => {
      // 不在工作区加载完成时运行代码
      // 不在拖动过程中运行代码，可能存在无效状态
      if (
        e.isUiEvent ||
        e.type == Blockly.Events.FINISHED_LOADING ||
        e.type == Blockly.Events.BLOCK_DRAG
      ) {
        return;
      }

      // 保存工作区状态
      save(this.workspace);

      // 更新代码显示
      this.codePanel.updateCode();
    });
  }
}
